"""
Raid api
"""


import re
import json

from .command import raw_command
from .argument import build_args
from redfishtoollib import main


# get physical disks
def get_physical_disk():
    args = build_args()
    cmd = raw_command(args, 'GET', '/redfish/v1/Chassis', None)
    res = main(cmd)
    try:
        urls = json.loads(res)
    except ValueError:
        urls = {}
    if len(urls.get('Members', [])) > 0:
        base_url = urls.get('Members', [])[0].get('@odata.id')
        cmd = raw_command(args, 'GET', base_url, None)
        res = main(cmd)
        try:
            drives = json.loads(res)
        except ValueError:
            drives = {}
        drives = drives['Links']['Drives']
        disks = []
        for i in drives:
            cmd = raw_command(args, 'GET', i.get('@odata.id'), None)
            res = main(cmd)
            try:
                disk = json.loads(res)
            except ValueError:
                disk = {}
            disk_name = disk.get('Name', '')
            disk_id = re.findall(r'\d+', disk_name)[0]
            disk_state = disk.get('Status', {}).get('State')
            disks.append({
                'id': disk_id,
                'name': disk_name,
                'state': disk_state
            })
        print(json.dumps(disks, indent=4))


# create virtual disks
# params: json string
# format: ""
# todo: params define
def create_virtual_disk():
    args = build_args()
    cmd = raw_command(args, 'GET', '/redfish/v1/Systems', None)
    res = main(cmd)
    try:
        urls = json.loads(res)
    except ValueError:
        urls = {}
    if len(urls.get('Members', [])) > 0:
        base_url = urls.get('Members', [])[0].get('@odata.id')
        cmd = raw_command(args, 'GET', base_url + '/Storages', None)
        res = main(cmd)
        try:
            controller = json.loads(res)
        except ValueError:
            controller = {}
        print(controller)
        url = controller["Members"][0].get('@odata.id') if len(controller['Members']) > 0 else ''
        if url:
            cmd = raw_command(args, 'GET', url + '/Volumes', None)
            res = main(cmd)
            print(res)